<template>
    <div class="job-list-container">
        <div class="header-bar">
            <h2>任务列表</h2>
            <div class="header-actions">
                <el-button type="primary" @click="handleCreate">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    创建任务
                </el-button>
                <el-button @click="refreshData">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </div>
        </div>

        <!-- 筛选条件 -->
        <el-card class="filter-card" shadow="never">
            <el-form :model="filterForm" inline>
                <el-form-item label="任务状态">
                    <el-select v-model="filterForm.status" placeholder="请选择状态" clearable @change="handleFilter">
                        <el-option label="全部" value="" />
                        <el-option label="活跃" value="ACTIVE" />
                        <el-option label="暂停" value="PAUSED" />
                        <el-option label="停止" value="STOPPED" />
                    </el-select>
                </el-form-item>
                <el-form-item label="任务名称">
                    <el-input v-model="filterForm.taskName" placeholder="请输入任务名称" clearable @input="handleFilter"
                        style="width: 200px" />
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 任务表格 -->
        <el-card shadow="never">
            <el-table v-loading="loading" :data="filteredTasks" stripe style="width: 100%" class="fixed-table">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="taskName" label="任务名称" min-width="150" />
                <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
                <el-table-column prop="cronExpression" label="Cron表达式" min-width="120" />
                <el-table-column prop="targetClass" label="目标类" min-width="180" show-overflow-tooltip />
                <el-table-column prop="targetMethod" label="目标方法" min-width="120" />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">
                            {{ getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="executionCount" label="执行次数" width="100" />
                <el-table-column prop="lastExecutedAt" label="最后执行时间" width="160">
                    <template #default="{ row }">
                        {{ formatDateTime(row.lastExecutedAt) }}
                    </template>
                </el-table-column>
                <el-table-column prop="nextExecutionAt" label="下次执行时间" width="160">
                    <template #default="{ row }">
                        {{ formatDateTime(row.nextExecutionAt) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="280" fixed="right">
                    <template #default="{ row }">
                        <el-button-group>
                            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button size="small" type="success" @click="handleExecute(row)"
                                :loading="executingIds.includes(row.id)">
                                立即执行
                            </el-button>
                            <el-dropdown @command="(command) => handleStatusAction(command, row)">
                                <el-button size="small" type="warning">
                                    状态操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item command="start"
                                            :disabled="row.status === 'ACTIVE'">启动</el-dropdown-item>
                                        <el-dropdown-item command="pause"
                                            :disabled="row.status !== 'ACTIVE'">暂停</el-dropdown-item>
                                        <el-dropdown-item command="resume"
                                            :disabled="row.status !== 'PAUSED'">恢复</el-dropdown-item>
                                        <el-dropdown-item command="stop"
                                            :disabled="row.status === 'STOPPED'">停止</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { jobTaskApi } from '@/api/jobs'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tasks = ref([])
const executingIds = ref([])

// 筛选表单
const filterForm = reactive({
    status: '',
    taskName: ''
})

// 筛选后的任务列表
const filteredTasks = computed(() => {
    let result = tasks.value

    if (filterForm.status) {
        result = result.filter(task => task.status === filterForm.status)
    }

    if (filterForm.taskName) {
        result = result.filter(task =>
            task.taskName.toLowerCase().includes(filterForm.taskName.toLowerCase())
        )
    }

    return result
})

// 获取任务列表
const loadTasks = async () => {
    loading.value = true
    try {
        const response = await jobTaskApi.getAllTasks()
        tasks.value = response.data || []
    } catch (error) {
        console.error('加载任务列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 刷新数据
const refreshData = () => {
    loadTasks()
}

// 筛选处理
const handleFilter = () => {
    // 筛选逻辑在computed中处理
}

// 创建任务
const handleCreate = () => {
    router.push('/jobs/create')
}

// 编辑任务
const handleEdit = (row) => {
    router.push(`/jobs/edit/${row.id}`)
}

// 立即执行任务
const handleExecute = async (row) => {
    if (executingIds.value.includes(row.id)) return

    executingIds.value.push(row.id)
    try {
        await jobTaskApi.executeTask(row.id)
        ElMessage.success('任务执行成功')
        await loadTasks() // 刷新列表以获取最新的执行信息
    } catch (error) {
        console.error('执行任务失败:', error)
    } finally {
        executingIds.value = executingIds.value.filter(id => id !== row.id)
    }
}

// 状态操作
const handleStatusAction = async (command, row) => {
    try {
        const actionMap = {
            start: { api: jobTaskApi.startTask, message: '任务启动成功' },
            pause: { api: jobTaskApi.pauseTask, message: '任务暂停成功' },
            resume: { api: jobTaskApi.resumeTask, message: '任务恢复成功' },
            stop: { api: jobTaskApi.stopTask, message: '任务停止成功' }
        }

        const action = actionMap[command]
        if (action) {
            await action.api(row.id)
            ElMessage.success(action.message)
            await loadTasks() // 刷新列表
        }
    } catch (error) {
        console.error(`${command}任务失败:`, error)
    }
}

// 删除任务
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除任务 "${row.taskName}" 吗？此操作不可恢复。`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await jobTaskApi.deleteTask(row.id)
        ElMessage.success('任务删除成功')
        await loadTasks()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除任务失败:', error)
        }
    }
}

// 获取状态标签类型
const getStatusType = (status) => {
    const typeMap = {
        ACTIVE: 'success',
        PAUSED: 'warning',
        STOPPED: 'danger'
    }
    return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const textMap = {
        ACTIVE: '活跃',
        PAUSED: '暂停',
        STOPPED: '停止'
    }
    return textMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return '-'
    const date = new Date(dateTime)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    })
}

// 组件挂载时加载数据
onMounted(() => {
    loadTasks()
})
</script>

<style scoped>
.job-list-container {
    padding: 0 20px;
    width: 100%;
    box-sizing: border-box;
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 0 5px;
}

.header-bar h2 {
    margin: 0;
    color: #303133;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.filter-card {
    margin-bottom: 15px;
}

.filter-card :deep(.el-card__body) {
    padding: 12px 15px;
}

/* 表格容器优化 */
.filter-card,
.filter-card+.el-card {
    width: 100%;
}

:deep(.el-table) {
    width: 100% !important;
}

/* 表格水平滚动和固定操作列 */
.fixed-table {
    overflow-x: auto;
}

:deep(.fixed-table .el-table__body-wrapper) {
    overflow-x: auto;
}

:deep(.fixed-table .el-table__fixed-right) {
    right: 0 !important;
}

/* 操作按钮不换行 */
:deep(.el-button-group) {
    white-space: nowrap;
    display: inline-flex;
}

:deep(.el-button-group .el-button) {
    flex-shrink: 0;
}

:deep(.el-dropdown) {
    display: inline-block;
}

:deep(.el-card__body) {
    padding: 15px;
}

/* 响应式布局 */


@media (max-width: 768px) {
    .job-list-container {
        padding: 0 10px;
    }

    .header-bar {
        flex-direction: column;
        gap: 15px;
        align-items: flex-start;
    }

    .header-bar h2 {
        font-size: 18px;
    }

    .header-actions {
        width: 100%;
        justify-content: flex-end;
    }

    .filter-card :deep(.el-form) {
        flex-direction: column;
    }

    .filter-card :deep(.el-form-item) {
        margin-right: 0;
        margin-bottom: 10px;
        width: 100%;
    }

    .filter-card :deep(.el-select),
    .filter-card :deep(.el-input) {
        width: 100% !important;
    }

    /* 移动端表格操作按钮优化 */
    :deep(.el-button-group) {
        display: flex !important;
        flex-wrap: wrap !important;
        gap: 4px;
        white-space: normal !important;
    }

    :deep(.el-button-group .el-button) {
        margin: 0;
        font-size: 12px;
        padding: 4px 8px;
        flex-shrink: 1 !important;
    }

    :deep(.el-dropdown) {
        width: 100%;
    }

    :deep(.el-dropdown .el-button) {
        width: 100%;
        font-size: 12px;
        padding: 4px 8px;
    }
}

@media (max-width: 480px) {
    .job-list-container {
        padding: 0;
    }

    .header-bar {
        padding: 0;
        margin-bottom: 10px;
    }

    .header-bar h2 {
        font-size: 16px;
    }

    .header-actions .el-button {
        font-size: 12px;
        padding: 6px 12px;
    }

    .header-actions .el-button span {
        display: none;
    }

    .filter-card :deep(.el-card__body) {
        padding: 10px;
    }

    /* 表格在移动端的优化 */
    :deep(.el-table) {
        font-size: 12px;
    }

    :deep(.el-table .el-table__cell) {
        padding: 6px 4px;
    }

    :deep(.el-table .cell) {
        word-break: break-all;
        line-height: 1.2;
    }

    /* 隐藏部分列在移动端 */
    :deep(.el-table__column--hidden) {
        display: none !important;
    }

    /* 操作列优化 */
    :deep(.el-button-group) {
        flex-direction: column;
        width: 100%;
    }

    :deep(.el-button-group .el-button) {
        width: 100%;
        margin-bottom: 2px;
        font-size: 11px;
        padding: 3px 6px;
    }
}
</style>